#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Advanced encoding fix script
"""

import os
import sys
import shutil
from pathlib import Path

def detect_encoding(file_path):
    """Detect file encoding"""
    encodings = ['utf-8', 'gbk', 'gb2312', 'utf-16', 'latin-1']
    
    for encoding in encodings:
        try:
            with open(file_path, 'r', encoding=encoding) as f:
                f.read()
            return encoding
        except UnicodeDecodeError:
            continue
    
    return None

def fix_file_encoding(file_path):
    """Fix encoding issues in a file"""
    try:
        # Detect encoding
        detected_encoding = detect_encoding(file_path)
        if not detected_encoding:
            print(f"? Cannot detect encoding for {file_path}")
            return False
        
        # Read with detected encoding
        with open(file_path, 'r', encoding=detected_encoding) as f:
            content = f.read()
        
        # Create backup
        backup_path = file_path + '.backup'
        shutil.copy2(file_path, backup_path)
        
        # Write back with utf-8
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"? Fixed encoding for {file_path} (converted from {detected_encoding})")
        return True
        
    except Exception as e:
        print(f"? Failed to fix encoding for {file_path}: {e}")
        return False

def create_clean_copy(file_path, new_path):
    """Create a clean copy of a file"""
    try:
        # Detect encoding
        detected_encoding = detect_encoding(file_path)
        if not detected_encoding:
            print(f"? Cannot detect encoding for {file_path}")
            return False
        
        # Read with detected encoding
        with open(file_path, 'r', encoding=detected_encoding) as f:
            content = f.read()
        
        # Write to new file with utf-8
        with open(new_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"? Created clean copy: {new_path}")
        return True
        
    except Exception as e:
        print(f"? Failed to create clean copy for {file_path}: {e}")
        return False

def main():
    """Main function"""
    print("? Advanced encoding fix tool...")
    
    # Files to check
    files_to_check = [
        'gui_app.py',
        'mystep1v2.py',
        'gui_app.spec'
    ]
    
    print("\n1. Fixing existing files...")
    success_count = 0
    for file_path in files_to_check:
        if Path(file_path).exists():
            if fix_file_encoding(file_path):
                success_count += 1
    
    print(f"\n? Results: {success_count}/{len(files_to_check)} files fixed")
    
    print("\n2. Creating clean English version...")
    if Path('gui_app.py').exists():
        create_clean_copy('gui_app.py', 'gui_app_clean.py')
    
    print("\n3. Creating minimal build script...")
    minimal_script = '''@echo off
echo Building VideoProcessingApp...
echo.

REM Install PyInstaller
pip install pyinstaller

REM Clean
if exist build rmdir /s /q build
if exist dist rmdir /s /q dist

REM Build
pyinstaller --onefile --windowed --name VideoProcessingApp --hidden-import cv2 --hidden-import ultralytics --hidden-import torch --hidden-import torchvision --hidden-import PIL --hidden-import tkinter --hidden-import mystep1v2 --add-data "mystep1v2.py;." gui_app_clean.py

if errorlevel 1 (
    echo Build failed
) else (
    echo Build successful! exe file: dist\\VideoProcessingApp.exe
)

pause
'''
    
    with open('build_clean.bat', 'w', encoding='utf-8') as f:
        f.write(minimal_script)
    
    print("? Created build_clean.bat")
    
    if success_count == len(files_to_check):
        print("\n? All files encoding issues fixed!")
    else:
        print("\n?? Some files may still have encoding issues")
    
    print("\n? Next steps:")
    print("1. Try running build_clean.bat")
    print("2. Or use build_english.bat for English GUI version")
    print("3. Or manually run: pyinstaller --onefile --windowed gui_app_clean.py")

if __name__ == "__main__":
    main() 